package com.zgw.fireline.base.controls;

import java.util.EventObject;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.zgw.fireline.base.dataset.Dataset;
import com.zgw.fireline.base.dataset.DatasetListener;

public class DataText extends Composite {
	Shell shell;
	Dataset input;
	private String textExpr;
	private Text text;

	public DataText(Composite parent, int style, Dataset set, String textExpr) {
		super(parent, style);
		super.setBackground(getParent().getBackground());
		this.input = set;
		this.textExpr = textExpr;
		GridLayout gridLayout = new GridLayout(2, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.marginWidth = 0;
		gridLayout.marginHeight = 0;
		setLayout(gridLayout);

		text = new Text(this, SWT.BORDER);
		text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		Button btnNewButton = new Button(this, SWT.TOGGLE);
		btnNewButton.setToolTipText("点击选择数据源");
		btnNewButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false,
				true, 1, 1));
		btnNewButton.setText("...");
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				openSelectionDlg();
			}
		});
		if (input != null) {
			final DatasetListener listener = new DatasetListener() {
				public void rowSetChanged(EventObject event) {
					refresh();
				}

				public void rowChanged(EventObject event) {

				}

				public void cursorMoved(EventObject event) {
					refresh();
				}
			};
			input.addDatasetListener(listener);
			addDisposeListener(new DisposeListener() {
				public void widgetDisposed(DisposeEvent e) {
					input.removeDatasetListener(listener);
				}
			});
			refresh();
		}
	}

	// 打开数据源选择对话框
	protected void openSelectionDlg() {
		shell = new Shell(getShell(), SWT.DIALOG_TRIM);
		DataTable table = new DataTable(shell, SWT.NONE, input);
		
	}

	protected void refresh() {
		if (input != null) {
			text.setText(input.getStringForExpr(textExpr));
		}
	}

	@Override
	public void setFont(Font font) {
		text.setFont(font);
	}

	@Override
	public void setBackground(Color color) {
		text.setBackground(color);
		super.setBackground(getParent().getBackground());
	}

	@Override
	public void setForeground(Color color) {
		text.setForeground(color);
	}

	@Override
	protected void checkSubclass() {
	}

}
